from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
#from google.appengine.ext.webapp.util import run_wsgi_app
import os

# SITE http://myzope.kedai.com.my/blogs/kedai/236
import wsgiref.handlers
import facebook
from models import database_type
from secret import API_KEY
from secret import SECRET_KEY

class BaseHandler(webapp.RequestHandler):
	def get(self):
		self.facebookapi = facebook.Facebook(API_KEY,SECRET_KEY)
		if not self.facebookapi.check_connect_session(self.request):
			dummy=database_type.Dummy(text='nops')
			template_values={"dummy":dummy}
			self.template_render('../html/index.html',template_values)
			return
		try:
			self.user = self.facebookapi.users.getInfo(
			[self.facebookapi.uid],
			['uid', 'name', 'birthday', 'relationship_status'])[0]
		except facebook.FacebookError:
			dummy=database_type.Dummy(text='nops')
			template_values={"User":dummy}
			self.template_render('../html/index.html',template_values)
			return
		self.get_secure()
	
	def template_render(self,template_path,template_values):
		path=os.path.join(os.path.dirname(__file__),template_path)
		self.response.out.write(template.render(path,template_values))



class MainPage(BaseHandler):
	def get_secure(self):
		self.user = self.facebookapi.users.getInfo(
        		[self.facebookapi.uid],
		        ['uid', 'name', 'birthday', 'relationship_status'])[0]
		template_values = {
			"profile" : self.user['name']
			}
		self.template_render('../html/index_logged.html',template_values)
	
def main():
	application=webapp.WSGIApplication([('/',MainPage)],debug=True)
	#run_wsgi_app(application)
	wsgiref.handlers.CGIHandler().run(application)

if __name__=='__main__':
	main()
